<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    public function index() {
        $data=Cookie::get(md5('user'));
        if($data!==null){
            $userObj=Crypt::decrypt($data);
            $ret = DB::table('user')->where('user_name', '=', $userObj->user_name)->where('password', '=', $userObj->password)->where('status', '=', 1)->first();
            if(is_object($ret)&&!empty($ret->id)){
//                request()->session()->set(md5('user'),$ret);
                Cache::put(md5('user'),$ret,72000);
                DB::table('user')->where('id',$ret->id)->update(['last_time'=>date('Y-m-d H:i:s',time())]);
                return redirect('/admin');
            }
        }

        return view('admin.login.login');
    }

    public function login(Request $request) {
        $data     = $request->input();
        $ret = DB::table('user')->where('user_name', '=', $data['user'])->where('status', '=', 1)->first();
        if($ret !== null && is_object($ret) && isset($ret->id)) {
            if(md5($data['password']) == $ret->password) {
//                $request->session()->set(md5('user'), $ret);
                Cache::put(md5('user'),$ret,72000);
                if($data['remember']) {
                    Cookie::queue(md5('user'), Crypt::encrypt($ret), time() + 7200);
                } else {
                    Cookie::forget(md5('user'));
                }
                DB::table('user')->where('id',$ret->id)->update(['last_time'=>date('Y-m-d H:i:s',time())]);
                return response()->json(['status' => true,'data'=>Crypt::encrypt($ret->user_name)]);
            }
            return response()->json(['status' => false, 'data' => '密码错误']);
        }
        return response()->json(['status' => false, 'data' => '用户名错误']);
    }

    /**
     *
     * @param Request $request
     */
    public function check(Request $request) {
        $data     = $request->input();
        if(!isset($data)){
            return response()->json(['status' => false]);
        }
        $token=Crypt::decrypt($data['token']);
//        $userInfo=$request->session()->get(md5('user'));
        $userInfo=Cache::get(md5('user'));
        if($userInfo!=null&&$userInfo->user_name==$token){
            return response()->json(['status' => true]);
        }else{
            return response()->json(['status' => false]);
        }
    }

    /**
     * 退出登陆
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logOut(Request $request){
        $request->session()->forget(md5('user'));
        Cookie::queue(md5('user'),null,-1);
        return redirect('/login');
    }
}
